package com.zzb.weikeautosign.param;

import com.zzb.weikeautosign.SecurityUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by 瑱彬 on 2016/1/15.
 */
public abstract class BaseParam {
    protected String sign;
    private String deviceModel  = "MI";
    private String appVersion = "5.1";
    private String device = "1";
    private String timestamp;
    public String getSign(){
        return sign;
    }

    public String getTimestamp() {
        if(timestamp == null){
            timestamp = System.currentTimeMillis()+"";
        }
        return timestamp;
    }

    public String getDeviceModel() {
        return deviceModel;
    }

    public String getAppVersion() {
        return appVersion;
    }

    public String getDevice() {
        return device;
    }

    public TreeMap<String,String> toMap() {
        Class clazz = this.getClass();
        Field [] subField = clazz.getDeclaredFields();
        Field [] fields = (Field[]) ArrayUtils.addAll(subField,clazz.getSuperclass().getDeclaredFields());
        TreeMap <String,String> map = new TreeMap<>();
        List<Field> fieldList = new ArrayList<>();
        CollectionUtils.addAll(fieldList,fields);
        fieldList.stream().filter(field1 -> !Modifier.isStatic(field1.getModifiers())).forEach(field ->  {
            String value = null;
            try {
                Method method = clazz.getMethod("get"+ StringUtils.capitalize(field.getName()));
                value = (String) method.invoke(this);
                map.put(field.getName(),value);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        });
        return map;
    }
    public String toParam(){
        StringBuilder sb = new StringBuilder("");
        TreeMap<String,String> params = toMap();
        try {
            for(Map.Entry<String, String> entry : params.entrySet()){
                    sb.append(entry.getKey()).append('=')
                            .append(URLEncoder.encode(entry.getValue(), "utf-8")).append('&');
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }
}
